package com.huffman.smart_picture.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huffman.smart_picture.annotation.CheckAnyAuth;
import com.huffman.smart_picture.annotation.CheckAnyRole;
import com.huffman.smart_picture.auth.constants.SpaceUserPermissionConstant;
import com.huffman.smart_picture.auth.constants.SpaceUserRoleConstant;
import com.huffman.smart_picture.common.auth.AuthConstant;
import com.huffman.smart_picture.common.auth.SessionContext;
import com.huffman.smart_picture.common.auth.annotation.CheckRole;
import com.huffman.smart_picture.common.auth.annotation.LoginRequired;
import com.huffman.smart_picture.common.UserSession;
import com.huffman.smart_picture.common.base.reponse.PageQueryResult;
import com.huffman.smart_picture.common.base.reponse.ResponseResult;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.domain.constants.CommonConstant;
import com.huffman.smart_picture.domain.entity.Space;
import com.huffman.smart_picture.domain.enums.SpaceLevelEnum;
import com.huffman.smart_picture.domain.request.space.*;
import com.huffman.smart_picture.domain.vo.space.AbbreviationSpaceVo;
import com.huffman.smart_picture.domain.vo.space.SpaceLevelVo;
import com.huffman.smart_picture.domain.vo.space.SpaceUserVo;
import com.huffman.smart_picture.domain.vo.space.SpaceVo;
import com.huffman.smart_picture.service.SpaceService;
import com.huffman.smart_picture.utils.ResponseUtil;
import com.huffman.smart_picture.utils.ThrowUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SessionContext sessionContext;

    @Resource
    private SpaceService spaceService;

    @PostMapping("/create")
    @ApiOperation(value = "创建空间")
    @LoginRequired
    public ResponseResult<Long> createSpace(@RequestBody SpaceCreateRequest spaceCreateRequest,HttpServletRequest httpServletRequest) {
        // 校验参数
        ThrowUtil.throwIf(spaceCreateRequest == null, ErrorEnum.PARAM_EMPTY, "请求参数为空");
        Long spaceId = spaceService.createSpace(spaceCreateRequest, httpServletRequest);
        return ResponseUtil.success(spaceId);
    }

    @GetMapping("/search/{id}")
    @ApiOperation(value = "查询空间信息")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult<Space> searchSpace(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        Space space = spaceService.getById(id);
        ThrowUtil.throwIf(space == null, ErrorEnum.RESOURCE_NOT_FIND, "空间不存在");
        return ResponseUtil.success(space);
    }

    @GetMapping("/search/vo/{id}")
    @ApiOperation(value = "查询空间信息")
    @CheckAnyRole(roles = {SpaceUserRoleConstant.VIEWER, SpaceUserRoleConstant.EDITOR, SpaceUserRoleConstant.CREATOR})
    public ResponseResult<SpaceVo> searchSpaceVo(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        SpaceVo spaceVo = spaceService.searchSpaceVo(id);
        return ResponseUtil.success(spaceVo);
    }

    @GetMapping("/abbreviation")
    @ApiOperation(value = "获取用户所有缩略空间信息")
    @LoginRequired
    public ResponseResult<List<AbbreviationSpaceVo>> getAbbreviationSpaceVo() {
        UserSession userSession = sessionContext.getUserSession();
        return ResponseUtil.success(spaceService.getAbbreviationSpaceVo(userSession.getId()));
    }

    @GetMapping("/user/{id}")
    @ApiOperation(value = "获取当前用户在指定空间的权限信息")
    @LoginRequired
    public ResponseResult getSpaceUserAuth(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id == null || id <= 0, ErrorEnum.PARAM_EMPTY, "空间id不存在");
        UserSession userSession = sessionContext.getUserSession();
        SpaceUserVo spaceUserVo = spaceService.getSpaceUserAuth(id, userSession);
        return ResponseUtil.success(spaceUserVo);
    }

    @GetMapping("/users/{id}")
    @ApiOperation(value = "获取空间所有用户部分信息")
    @CheckAnyAuth(auths = {SpaceUserPermissionConstant.SPACE_MANAGE})
    public ResponseResult getSpaceUsers(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id == null || id <= 0, ErrorEnum.PARAM_EMPTY, "空间id不存在");
        List<SpaceUserVo> spaceUserVos = spaceService.getSpaceUsers(id);
        return ResponseUtil.success(spaceUserVos);
    }

    @PostMapping("/invite")
    @ApiOperation(value = "空间成员邀请")
    @CheckAnyAuth(auths = {SpaceUserPermissionConstant.SPACE_MANAGE})
    public ResponseResult inviteUserToSpace(@RequestBody SpaceInviteUserRequest spaceInviteUserRequest, HttpServletRequest httpServletRequest) {
        ThrowUtil.throwIf(spaceInviteUserRequest == null, ErrorEnum.PARAM_EMPTY, "参数为空");
        Long spaceId = spaceInviteUserRequest.getId();
        String username = spaceInviteUserRequest.getUsername();
        Integer spaceUserRole = spaceInviteUserRequest.getSpaceUserRole();
        ThrowUtil.throwIf(spaceId == null || spaceId <= 0, ErrorEnum.PARAM_EMPTY, "空间id不存在");
        ThrowUtil.throwIf(spaceUserRole == null, ErrorEnum.PARAM_EMPTY, "角色类型为空");
        ThrowUtil.throwIf(StrUtil.isBlank(username), ErrorEnum.PARAM_EMPTY, "用户名为空");
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        boolean res = spaceService.inviteUser(spaceInviteUserRequest, userSession);
        return ResponseUtil.success(res);
    }

    @PostMapping("/delete/{id}")
    @ApiOperation(value = "删除空间")
    @LoginRequired
    public ResponseResult deleteSpace(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        UserSession userSession = sessionContext.getUserSession();
        //判断空间是否存在
        Space space = spaceService.getById(id);
        ThrowUtil.throwIf(space == null, ErrorEnum.RESOURCE_NOT_FIND, "当前空间不存在");
        //仅支持管理员 本人删除
        boolean condition = userSession.isAdmin() || space.getId().equals(userSession.getId());
        ThrowUtil.throwIf(!condition, ErrorEnum.NO_AUTH, "删除失败，权限不足");
        spaceService.removeById(id);
        return ResponseUtil.success();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新空间")
    @LoginRequired
    public ResponseResult<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        //校验参数是否合法
        ThrowUtil.throwIf(spaceUpdateRequest == null, ErrorEnum.PARAM_EMPTY, "参数为空");
        Long id = spaceUpdateRequest.getId();
        ThrowUtil.throwIf(id == null || id <= 0, ErrorEnum.PARAM_ILLICIT, "空间id非法");
        Space space = SpaceUpdateRequest.convert(spaceUpdateRequest);
        // 填充额度数据
        spaceService.fillSpaceBySpaceLevel(space);
        spaceService.validSpace(space, false);
        // 判断数据是否存在
        Space oldSpace = spaceService.getById(id);
        ThrowUtil.throwIf(oldSpace == null, ErrorEnum.RESOURCE_NOT_FIND, "空间不存在");
        // 校验权限
        UserSession userSession = sessionContext.getUserSession();
        //仅支持管理员 本人更新
        boolean condition = userSession.isAdmin() || space.getUserId().equals(userSession.getId());
        ThrowUtil.throwIf(!condition, ErrorEnum.NO_AUTH, "更新失败，权限不足");

        boolean res = spaceService.updateById(space);
        ThrowUtil.throwIf(!res, ErrorEnum.SYSTEM_ERROR, "系统错误,操作失败");
        return ResponseUtil.success(true);
    }

    @PostMapping("/page")
    @ApiOperation(value = "分页查询")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult pageQuery(@RequestBody SpacePageQueryRequest spacePageQueryRequest) {
        ThrowUtil.throwIf(spacePageQueryRequest == null, ErrorEnum.PARAM_EMPTY, "查询参数为空");
        String spaceName = spacePageQueryRequest.getSpaceName();
        Integer spaceLevel = spacePageQueryRequest.getSpaceLevel();
        Integer pageNum = spacePageQueryRequest.getPageNum();
        Integer pageSize = spacePageQueryRequest.getPageSize();
        String sortField = spacePageQueryRequest.getSortField();
        String sort = spacePageQueryRequest.getSort();

        ThrowUtil.throwIf(pageNum < 1, ErrorEnum.PARAM_ILLICIT, "请求参数错误");
        ThrowUtil.throwIf(pageSize > 20, ErrorEnum.PARAM_ILLICIT, "请求参数错误");

        // 版本查询条件
        boolean querySpaceLevelCondition = spaceLevel != null && SpaceLevelEnum.getEnumByValue(spaceLevel) != null;
        QueryWrapper<Space> spaceQueryWrapper = new QueryWrapper<>();
        spaceQueryWrapper.like(StringUtils.hasText(spaceName), "space_name", spaceName)
                .eq(querySpaceLevelCondition, "space_level", spaceLevel)
                .orderBy(StringUtils.hasText(sortField), CommonConstant.SORT_ASC.equals(sort), sortField);
        Page<Space> page = new Page<>(pageNum, pageSize);

        spaceService.page(page, spaceQueryWrapper);
        PageQueryResult<Space> pageQueryResult = new PageQueryResult<>();
        pageQueryResult.setData(page.getRecords());
        pageQueryResult.setPages(page.getPages());
        pageQueryResult.setTotal(page.getTotal());
        return ResponseUtil.success(pageQueryResult);
    }

    @GetMapping("/list/level")
    @ApiOperation(value = "空间级别查询")
    public ResponseResult<List<SpaceLevelVo>> listSpaceLevel() {
        List<SpaceLevelVo> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevelVo(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResponseUtil.success(spaceLevelList);
    }
}
